package com.caihao.onenote.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caihao.onenote.constant.MessageConstant;
import com.caihao.onenote.constant.StatusConstant;
import com.caihao.onenote.dto.UserDTO;
import com.caihao.onenote.entity.User;
import com.caihao.onenote.exception.PasswordErrorException;
import com.caihao.onenote.mapper.UserMapper;
import com.caihao.onenote.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.security.auth.login.AccountLockedException;
import javax.security.auth.login.AccountNotFoundException;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    //用户登录
    @Override
    public User login(UserDTO userDTO) throws AccountNotFoundException, AccountLockedException {

        String username = userDTO.getUsername();
        String password = userDTO.getPassword();

        //根据用户名查询用户数据
        User user = userMapper.getUserByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传过来的明文密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (user.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return user;
    }
}
